<?php


namespace app\common\helper;

use Config;

class Message
{
    protected $config = null;
    protected $template = null;

    public function __construct()
    {
        $this->config = Config::get('message.');
        $this->template = "trade";
    }

    // 设置模板类型
    public function set($name = "")
    {
        if ($name) {
            $this->template = $name;
        }
        return $this;
    }

    // 获取模板
    public function get($code, $params = [])
    {
        $templateName = $this->template."_template";
        $charPreg = $this->config['placeholder_preg'];

        $config = $this->config[$templateName];
        $configArr = array_column($config, null, "id");
        $msgTemplate = $configArr[$code] ?? [];

        if (isset($msgTemplate['content']) && preg_match($charPreg, $msgTemplate['content'])) {
            $msgTemplate['content'] = $this->replaceText($msgTemplate['content'], $params);
        }

        return $msgTemplate;
    }

    // 替换模板信息
    protected function replaceText($content, $params)
    {
        $text = $content;
        if ($params) {
            $placeholder = $this->config['placeholder'];
            $chatBegin = $this->config['placeholder_begin'];
            $chatEnd = $this->config['placeholder_end'];

            foreach ($params as $key => $value) {
                if (is_array($value)) {
                    $value = array_values($value);
                }
                $text = str_replace($chatBegin . $placeholder.$key.$chatEnd, $value, $text);
            }
        }
        return $text;
    }

    // 获取所有配置
    public function getConfig()
    {
        return $this->config;
    }

}